<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>简易手机通讯录</title>
  <style>
    /* 简单样式设置，可按需调整 */
    form {
      width: 300px;
      margin: 0 auto;
      padding: 20px;
      border: 1px solid #ccc;
      border-radius: 5px;
    }

    label {
      display: block;
      margin-bottom: 5px;
    }

    input,
    textarea {
      width: 100%;
      padding: 8px;
      margin-bottom: 15px;
      border: 1px solid #ccc;
      border-radius: 3px;
    }
  </style>
</head>

<body>
  <form id="contactForm">
    <label for="name">姓名:</label>
    <input type="text" id="name" placeholder="请输入姓名">
    <label for="phone">电话:</label>
    <input type="text" id="phone" placeholder="请输入电话">
    <button type="button" id="addBtn">添加</button>
    <button type="button" id="queryBtn">查询</button>
    <button type="button" id="deleteBtn">删除</button>
    <button type="button" id="resetBtn">重置</button>
  </form>
  <textarea id="contactList" rows="5" cols="40"></textarea>

  <script>
    // 页面加载完成后执行
window.onload = function () {
  // 获取页面元素
  var addBtn = document.getElementById('addBtn');
  var queryBtn = document.getElementById('queryBtn');
  var deleteBtn = document.getElementById('deleteBtn');
  var resetBtn = document.getElementById('resetBtn');
  var nameInput = document.getElementById('name');
  var phoneInput = document.getElementById('phone');
  var contactListTextarea = document.getElementById('contactList');

  // 添加功能
  addBtn.onclick = function () {
    var name = nameInput.value;
    var phone = phoneInput.value;
    if (name && phone) {
      // 将联系人信息存储到 localStorage 中
      localStorage.setItem(name, phone);
      alert('添加成功');
      // 刷新通讯录列表显示
      displayContacts();
    } else {
      alert('姓名和电话不能为空');
    }
  };

  // 查询功能
  queryBtn.onclick = function () {
    var name = nameInput.value;
    if (name) {
      var phone = localStorage.getItem(name);
      if (phone) {
        phoneInput.value = phone;
      } else {
        alert('未找到该联系人');
      }
    } else {
      alert('请输入姓名');
    }
  };

  // 删除功能
  deleteBtn.onclick = function () {
    var name = nameInput.value;
    if (name) {
      localStorage.removeItem(name);
      alert('删除成功');
      // 刷新通讯录列表显示
      displayContacts();
    } else {
      alert('请输入姓名');
    }
  };

  // 重置功能
  resetBtn.onclick = function () {
    nameInput.value = '';
    phoneInput.value = '';
    contactListTextarea.value = '';
    localStorage.clear();
  };

  // 显示所有联系人的函数
  function displayContacts() {
    var contacts = '';
    for (var i = 0; i < localStorage.length; i++) {
      var name = localStorage.key(i);
      var phone = localStorage.getItem(name);
      contacts += name +'---'+ phone + '\n';
    }
    contactListTextarea.value = contacts;
  }

  // 页面加载时初始化显示通讯录
  displayContacts();
};
  </script>
</body>

</html>